package qe.spider.vo;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.PatternPool;
import cn.hutool.core.util.ReUtil;
import qe.spider.MainSelect;
import qe.spider.cfg.Factor;
import qe.spider.grab.ParseThsPool;
import qe.spider.grab.ParseThsStock;

import java.io.File;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

import static cn.hutool.core.date.DatePattern.NORM_DATE_PATTERN;

public class StockPool {

    private static Map<String, List<String>> poolStocks = new ConcurrentHashMap<>();

    private static List<File> latestPoolFile(String day) {
        Comparator<File> fileTimeDescComparator = (f1, f2) -> {
            Date d1 = DateUtil.parse(f1.getName(), "yyyy-MM-dd");
            Date d2 = DateUtil.parse(f2.getName(), "yyyy-MM-dd");
            return d2.compareTo(d1);
        };
        List<File> allDir = ParseThsPool.disks.stream().map(FileUtil::file)
                .filter(f -> f.isDirectory())
                .map(f -> Arrays.asList(f.listFiles())).flatMap(Collection::stream)
                .filter(f -> f.isDirectory() && ReUtil.isMatch("^\\d{4}-\\d{2}-\\d{2}$", f.getName()))
                .sorted(fileTimeDescComparator)
                .collect(Collectors.toList());
        if (MainSelect.factor.getPoolValidDays() > 0) {
            allDir = allDir.stream().filter(f -> {
                long diffDays = DateUtil.between(DateUtil.parse(day, NORM_DATE_PATTERN), DateUtil.parse(f.getName(), NORM_DATE_PATTERN), DateUnit.DAY);
                return f.getName().compareTo(day) <= 0 && diffDays <= MainSelect.factor.getPoolValidDays();    //今天与今天差0天；今天与昨天差1天
            }).collect(Collectors.toList());
        }
        return allDir;
    }

    public static Boolean stockInPool(String day, Stock stock) {
        if (!getPoolStocks(day).isEmpty()) {
            return getPoolStocks(day).contains(stock.getStock_code());
        } else {
            List<File> allFile = latestPoolFile(day).stream().map(path -> FileUtil.loopFiles(path, File::isFile))
                    .flatMap(Collection::stream)
                    .collect(Collectors.toList());
            List<String> codes = allFile.stream().map(f -> new ParseThsPool(f).parseAllLines()).flatMap(Collection::stream).collect(Collectors.toList());
            poolStocks.put(day, codes);
            return codes.contains(stock.getStock_code());
        }
    }

    public static List<String> getPoolStocks(String day) {
        if (poolStocks.containsKey(day)) return poolStocks.get(day);
        else return new ArrayList<>();
    }

    public static void main(String[] args) {
        MainSelect.factor = new Factor();
        List<File> f = StockPool.latestPoolFile("2024-06-03");
        Boolean s = stockInPool("2024-06-05", new Stock().code("600000"));
        System.out.println(s);
    }
}
